<template>
  <div>
    <el-dialog
        title="上传图片"
        :visible.sync="uploadVisible"
    >
      <div class="tipBox">
        <el-select v-model="catalog" clearable placeholder="选择目录,默认other">
          <el-option
              v-for="item in catalogList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-upload
          ref="uploadFile"
          name="fileData"
          :headers="importHeaders"
          :action="uploadAdminHost"
          :auto-upload="false">
        <el-button style="margin-top: 20px" slot="trigger" size="small" type="primary">选取本地图片</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">提交到服务器</el-button>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1MB</div>
        <div class="el-upload__tip" slot="tip" v-if="tip"><span style="color: red">图片格式有误或超过1MB</span></div>
      </el-upload>

    </el-dialog>
  </div>
</template>

<script>
import {Loading} from 'element-ui';
import {getToken} from '@/utils/auth'
import {upload} from "@/api/ossPicture";
import {categoryList} from "@/api/category";

export default {
  name: "blog-upload",
  props: {
    catalogList: {
      type: Array,
      default() {
        return [];
      }
    },
  },
  data() {
    return {
      uploadVisible: false,
      // uploadAdminHost: 'http://localhost:10000/uum-oss/api/v1/oss/upload', //上传地址
      uploadAdminHost: 'http://119.91.202.218:10000/uum-oss/api/v1/oss/upload', //上传地址
      importHeaders: {  //上传携带的请求头
        'Authorization': getToken()
      },
      uploadLoading: null, //文件上传loading
      cascaderValue: [],
      catalog: '',
      tip: false
    }
  },
  methods: {
    init() {
      this.uploadVisible = true
    },
    // 文件上传
    submitUpload() {
      let {uploadFiles} = this.$refs.uploadFile
      if (uploadFiles.length < 1) {
        this.$message.warning("请选择照片")
        return
      }
      let form = new FormData()
      let valida = false
      // 文件对象
      uploadFiles.map(file => {
        let isLt1M = file.raw.size / 1024 / 1024 < 1
            const isJPG = file.raw.type === 'image/jpeg';
            const isPNG = file.raw.type === 'image/png';
            if (!((isJPG || isPNG) && isLt1M)) {
              valida = true
              return
            }
        return form.append("fileData", file.raw);
      })

      if (valida) {
        this.tip = true;
      } else {
        this.tip = false;
        let catalog = this.catalog;
        if (!catalog) {
          //默认为other
          catalog = 'other'
        }
        this.openLoading()
        form.append('catalog',catalog)
        upload(form).then(res => {
          if (res.status) {
            this.closeLoading();
            this.uploadVisible = false
            this.$emit('handleQuery')
          }
        })
      }

    },
    /**
     * 自定义上传文件
     * @param fileList 文件列表
     * @param data 上传时附带的额外参数
     * @param url 上传的URL地址
     * @param success 成功回调
     * @param error 失败回调
     */
    uploadFiles({uploadFiles, headers, data, action, success, error}) {
      let form = new FormData()
      // 文件对象
      uploadFiles.map(file => {
            return form.append("fileData", file.raw)
          }
      )
      let xhr = new XMLHttpRequest()
      // 异步请求
      xhr.open("post", action, true)
      // 设置请求头
      xhr.setRequestHeader("Authorization", getToken());
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            success && success(xhr.responseText)
          } else {
            error && error(xhr.status)
          }
        }
      }
      xhr.send(form)
    },
    openLoading() {
      this.uploadLoading = Loading.service({
        lock: true,
        text: '正在努力上传中……'
      })
    },
    closeLoading() {
      this.uploadLoading.close()
    },
  }
}
</script>

<style scoped>

</style>
